//
//  YREmoticonViewController.swift
//  表情键盘
//
//  Created by cyr on 15/10/21.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

private let YREmoticonCellIdentifier = "YREmoticonCellIdentifier"

class YREmoticonViewController: UIViewController {
//    
    var selecetdEmoticonCallBack: (emoticon: YREmoticons) -> ()
    
    init(selectedEmoticon:(emoticon: YREmoticons) -> ()) {
        selecetdEmoticonCallBack = selectedEmoticon
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 监听方法
    func clickItem(item:UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

//        view.backgroundColor = UIColor.redColor()
        setupUI()
        
    }

    
      // MARK: - 设置界面
    func setupUI() {
        view.addSubview(toolbar)
        view.addSubview(collectionView)
        
        // 自动布局
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["cv": collectionView, "tb": toolbar]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        prepareToolbar()
        prepareCollectionView()
    }
    
 /// 准备工具栏
    private func prepareToolbar() {
        toolbar.tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        
        for p in package {
            items.append(UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            //设置弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    /**
    准备 CV
    */
    private func prepareCollectionView() {
        
        collectionView.registerClass(YREmoticonCell.self,forCellWithReuseIdentifier: YREmoticonCellIdentifier)
        
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.whiteColor()
    }
    
    
    // MARK: - 懒加载
    private lazy var toolbar = UIToolbar()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout:  YREmoticonLayout())
    private lazy var package = YREmoticonPackage.package
    
    // 表情键盘布局
    private class YREmoticonLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            let w = collectionView!.bounds.width / 7.0
            let y = (collectionView!.bounds.height - 3 * w) * 0.499
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false

        }
    }
}

// MARK: - 数据源
extension YREmoticonViewController: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = package[indexPath.section].emoticons![indexPath.item]
        
        selecetdEmoticonCallBack(emoticon: emoticon)
        
        if indexPath.section > 0 {
        YREmoticonPackage.addFavorate(emoticon)
        }
//        collectionView.reloadSections(NSIndexPath(index: 0))
        
    }
    
    // 返回表情包的数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return package.count
    }
    // 返回每个包中表情的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return package[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YREmoticonCellIdentifier, forIndexPath: indexPath) as! YREmoticonCell
        
        cell.emoticon = package[indexPath.section].emoticons![indexPath.item]
        
        return cell
        
    }
}

/// 表情 cell
private class YREmoticonCell: UICollectionViewCell {
    
    var emoticon: YREmoticons? {
        didSet {
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)

            emoticonButton.setTitle(emoticon!.emoji, forState: UIControlState.Normal)

////            // 判断是否是删除按钮
            if emoticon!.removeEmoticon {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
//            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        emoticonButton.userInteractionEnabled = false
        
        addSubview(emoticonButton)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载
    private lazy var emoticonButton = UIButton()
    
}